package com.sy.shiro;

import com.gok.persistence.service.BaseDao;
import com.sy.common.model.Juejinuser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by alvawen on 2017/11/2 0002.
 */
@Slf4j
public class MyUsernameRealm extends AuthorizingRealm {
    public static final String SEPARATOR = ":";

    @Resource
    private BaseDao baseDao;
/*
    @Resource
    private IBaseService baseService;*/

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernameToken;
    }

/*    public void removeUserAuthorizationInfoCache(String username) {
        SimplePrincipalCollection pc = new SimplePrincipalCollection();
        pc.add(username, super.getName());
        super.clearCachedAuthorizationInfo(pc);
    }*/

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        CachedUser cachedUser = (CachedUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = (SimpleAuthorizationInfo) cachedUser.getJsonObject().get("SimpleAuthorizationInfo");
        if(simpleAuthorizationInfo == null) {
            simpleAuthorizationInfo = doGetAuthorizationInfo(cachedUser);
            cachedUser.getJsonObject().put("SimpleAuthorizationInfo", simpleAuthorizationInfo);
        }
        log.info("Permissions:{}", simpleAuthorizationInfo.getStringPermissions());
        return simpleAuthorizationInfo;
    }

    private SimpleAuthorizationInfo doGetAuthorizationInfo(CachedUser cachedUser) {
        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
//        String sql = "deleted is null";
//        List<Role> roleList = baseDao.listQueryBySQL(sql, Role.class);
//        Map<Long, Role> roleMap = new HashMap<>();
//        boolean isAdmin = false;
//        for (Role role : roleList) {
//            roleMap.put(role.getId(), role);
//        }
//        List<DepartmentRole> departmentRoleList = baseDao.getMapper(DepartmentRoleMapper.class).getRolePermissionList(cachedUser.getUserId());
//        log.info("{}, {}", roleList.size(), departmentRoleList.size());
//        for (DepartmentRole departmentRole : departmentRoleList) {
//            Role role = roleMap.get(departmentRole.getRoleId());
//            if(role != null) {
//                authenticationInfo.addRole(role.getCode());
//                if("admin".equalsIgnoreCase(role.getCode())) {
//                    isAdmin = true;
//                }
//            } else {
//                log.warn("role is not exist, id={}", departmentRole.getRoleId());
//            }
//        }
//
//        if(isAdmin) {
//            authenticationInfo.addStringPermission("*:*:*:*");
//            return authenticationInfo;
//        }
//
//        List<RolePermission> rolePermissionList = baseDao.getMapper(RolePermissionMapper.class).getRolePermissionList(cachedUser.getUserId());
//        List<Permission> permissionList = baseDao.listQueryBySQL(sql, Permission.class);
//        Map<Long, Permission> permissionMap = new HashMap<>();
//        for (Permission permission : permissionList) {
//            permissionMap.put(permission.getId(), permission);
//        }
//        for (RolePermission member : rolePermissionList) {
//            Permission permission = permissionMap.get(member.getPermissionId());
//            if(permission != null) {
//                String permissionString = genPermissionStr(permission, member);
//                authenticationInfo.addStringPermission(permissionString);
//            }
//        }
        return authenticationInfo;
    }

//    private String genPermissionStr(Permission permission, RolePermission member) {
//        StringBuilder result = new StringBuilder();
//        result.append(permission.getGroupCode()).append(SEPARATOR).append(permission.getCode()).append(SEPARATOR);
//        result.append(member.getPermissionString());
//        if(member.getObjId() != null) {
//            result.append(SEPARATOR).append(member.getObjId());
//        }
//        return result.toString();
//    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernameToken token = (UsernameToken) authenticationToken;
        Juejinuser juejinuser = new Juejinuser();
        SimpleAuthenticationInfo info = null;

        StringBuffer hql = new StringBuffer();
        hql.append("from Juejinuser where phone='");
        hql.append(token.getPhone());
        hql.append("'");
        List<Juejinuser> juejinuserList = baseDao.listQuery(hql.toString(), Juejinuser.class);
        if( juejinuserList.size() >= 1 ){
            juejinuser = juejinuserList.get(0);
        }

        int  v = 0;
        if( juejinuser == null )
        {
            int a = 9;
            throw new AuthenticationException("user not exist");
        }else{
            int b = 8;

        }

        token.setUserId(juejinuser.getId());
        info =  new SimpleAuthenticationInfo(token, token.getCredentials(), getName());

        return info;
    }
}
